// 引入json模块
var util = require('../util/util');
// 使用连接池，提升性能
const MysqlPool = require('./pool');
const mysqlPool = new MysqlPool();
const pool = mysqlPool.getPool();


/*
sql:查询语句
values:参数 
*/
let poolPromiseQueryNoneRes = function (sql, values) {
    return new Promise((resolve, reject) => {
        pool.getConnection(function (ex, connection) {

            let result = {
                code: 501,
                message: '操作异常',
            }
            if (ex) {
                console.log(ex);
                reject({
                    code: 501,
                    message: ex,
                })
            }
            else {
                try {
                    connection.query(sql, values, function (err, result) {

                        if (err) {
                            console.log(err);
                            result = {
                                code: 501,
                                message: err,
                            }
                        }
                        else {
                            if (result != '') {
                                result = {
                                    code: 200,
                                    data: result
                                }
                            } else {
                                if (util.isArray(result))
                                    result = {
                                        code: 200,
                                        data: []
                                    }
                                else
                                    result = {
                                        code: 1,
                                        message: '操作失败!',
                                    }
                            }
                        }

                        connection.release();
                        connection.destroy();

                        resolve(result);
                    });

                } catch (ex) {
                    console.log(ex);
                    reject(ex);
                }

            }

        });
    }).catch(error => console.log(error))
}

module.exports = { poolPromiseQueryNoneRes }